<template>
  <div class="coupon-page">
    <div class="header">
      <h2>优惠券管理</h2>
      <div class="actions">
        <el-button type="primary" @click="goCreate">创建优惠券</el-button>
        <el-button @click="goRecords">查看发放记录</el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="优惠券名称">
          <el-input v-model="filterForm.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in couponTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="NOT_STARTED" />
            <el-option label="进行中" value="ONGOING" />
            <el-option label="已结束" value="FINISHED" />
            <el-option label="已失效" value="INVALID" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table
      :data="coupons"
      border
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
    >
      <el-table-column prop="name" label="优惠券名称" width="180" />
      <el-table-column prop="type" label="类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.type)">
            {{ getTypeName(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="value" label="优惠内容" width="180" />
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column prop="endTime" label="结束时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="statusMap[row.status].type">
            {{ statusMap[row.status].text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      @current-change="handlePageChange"
      style="margin-top: 20px; justify-content: flex-end;"
      layout="total, sizes, prev, pager, next, jumper"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCoupons } from '@/api/coupon'
import { COUPON_TYPES } from '@/api/coupon'

const router = useRouter()

// 优惠券类型选项
const couponTypes = [
  { value: COUPON_TYPES.NEW_USER, label: '新人券' },
  { value: COUPON_TYPES.FULL_REDUCTION, label: '满减券' },
  { value: COUPON_TYPES.DIRECT_REDUCTION, label: '立减券' },
  { value: COUPON_TYPES.PRODUCT, label: '商品优惠券' },
  { value: COUPON_TYPES.SHOP, label: '店铺优惠券' },
  { value: COUPON_TYPES.REPURCHASE, label: '复购券' },
  { value: COUPON_TYPES.FANS, label: '涨粉券' }
]

// 状态映射
const statusMap = {
  NOT_STARTED: { text: '未开始', type: 'info' },
  ONGOING: { text: '进行中', type: 'success' },
  FINISHED: { text: '已结束', type: 'warning' },
  INVALID: { text: '已失效', type: 'danger' }
}

// 获取类型名称
const getTypeName = (type) => {
  const found = couponTypes.find(item => item.value === type)
  return found ? found.label : type
}

// 获取标签类型
const getTagType = (type) => {
  switch (type) {
    case COUPON_TYPES.NEW_USER: return 'success'
    case COUPON_TYPES.FULL_REDUCTION: return ''
    case COUPON_TYPES.DIRECT_REDUCTION: return 'warning'
    case COUPON_TYPES.PRODUCT: return 'danger'
    case COUPON_TYPES.SHOP: return 'info'
    default: return ''
  }
}

// 筛选表单
const filterForm = ref({
  name: '',
  type: '',
  status: ''
})

// 分页
const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 优惠券列表
const coupons = ref([])
const loading = ref(false)

// 获取优惠券列表
const fetchCoupons = async () => {
  try {
    loading.value = true
    const params = {
      ...filterForm.value,
      page: pagination.value.current,
      size: pagination.value.size
    }
    const { data } = await getCoupons(params)
    coupons.value = data.list
    pagination.value.total = data.total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchCoupons()
}

// 重置搜索
const resetSearch = () => {
  filterForm.value = {
    name: '',
    type: '',
    status: ''
  }
  handleSearch()
}

// 分页变化
const handlePageChange = () => {
  fetchCoupons()
}

// 跳转创建页面
const goCreate = () => {
  router.push('/coupon/create')
}

// 跳转记录页面
const goRecords = () => {
  router.push('/coupon/records')
}

// 编辑
const handleEdit = (row) => {
  router.push(`/coupon/edit/${row.id}`)
}

// 删除
const handleDelete = (row) => {
  console.log('删除优惠券:', row.id)
  // 实际项目中这里应该调用删除API
  ElMessageBox.confirm('确定要删除该优惠券吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchCoupons()
  }).catch(() => {
    // 取消删除
  })
}

onMounted(() => {
  fetchCoupons()
})
</script>

<style scoped>
.coupon-page {
  background: #fff;
  border-radius: 12px;
  padding: 32px 40px;
  min-height: 400px;
  box-shadow: 0 2px 8px #f0f1f2;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 10px;
}
</style>